﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Kooboo.CMS.Common.Persistence.Non_Relational;
using Kooboo.CMS.Content.Models;
using Kooboo.CMS.Content.Persistence;
using Kooboo.CMS.Content.Query;
using Kooboo.CMS.Sites.View;
using Kooboo.CMS.Web.Areas.Contents.Controllers;
using Kooboo.Web.Mvc;
using Kooboo.Web.Script.Serialization;

namespace DemoModule.Controllers
{
    public class ReportController : ContentControllerBase
    {
        private string FormatedValue(object firstValue, object secendValue)
        {
            return String.Format("[\"{0}\",{1}]", (firstValue ?? "").ToString().Replace("\"", "\\\""), secendValue);
        }
        public ActionResult Preview(string uuid, string repositoryName, string folderName)
        {
            folderName = folderName ?? this.ControllerContext.RequestContext.GetRequestValue("Folder");
            ViewBag.Title = folderName + " readings Reports";
            TextFolder textFolder = new TextFolder(Repository, folderName).AsActual();
            IContentQuery<TextContent> query = textFolder.CreateQuery();
            IEnumerable<string> data;
            if (String.IsNullOrEmpty(uuid))
            {
                data = query.Select(it => FormatedValue(it["Title"], it["Readings"]));
            }
            else
            {
                string[] uuids = uuid.Split(',');
                IEnumerable<TextContent> selectedTextContent = query.Where(it => uuids.Contains(it.UUID));
                data = selectedTextContent.Select(it => FormatedValue(it["Title"], it["Readings"]));
            }
            ViewBag.Json = String.Join(",", data);
            return View();
        }

        public ActionResult PublishDate(string repositoryName, string folderName)
        {
            ViewBag.Title = folderName + " publishing date reports";
            folderName = folderName ?? this.ControllerContext.RequestContext.GetRequestValue("Folder");
            TextFolder textFolder = new TextFolder(Repository, folderName).AsActual();
            IContentQuery<TextContent> query = textFolder.CreateQuery();
            var group = query.GroupBy(it => it.UtcCreationDate.ToString("yyyy-MM-dd"));
            if (group.Count(it => it.Any()) > 15)
            {
                group = query.GroupBy(it => it.UtcCreationDate.ToString("yyyy-MM"));
            }
            var data = group.ToArray().Select(it =>
            {
                var firstOrDefault = it.FirstOrDefault();
                return firstOrDefault != null ? FormatedValue(firstOrDefault.UtcCreationDate.ToString("yyyy-MM-dd"), it.Count()) : null;
            });
            ViewBag.Json = String.Join(",", data);
            return View("Preview");
        }
    }
}
